package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Service
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    // 处理权限不足的异常
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        log.debug("权限不足!");
        // 设置HTTP相应状态为403,表示禁止访问
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 设置响应内容类型为JSON UTF-8编码
        response.setContentType("application/json;chartset=UTF-8");
        // 获取响应的打印手写,用于写入响应内容
        PrintWriter writer = response.getWriter();
        //  构建一个表示未登录的JSON结果对象
        JsonResult result = new JsonResult(StatusCode.NOT_LOGIN);
        // 将JSON结果兑现转换为JSON字符串并写入响应
        writer.write(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }
}
